// pages/product/product.js
var appInstance = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {

        product_id:0,
        image_list:[],
        image:'',
        description:"",
        name:'',
        price:0,
        special:0,
        sale:0,
        bnrHeight:0,
        cart_total:0,

        option_panel:{

            goto:'',
            notice:0,
            pindan_order:0 // 主拼单ID
        },
        specification:[],
        spec_object:[],  // 商品选项列表
        pindan_number:0,
        pindan:{

        },

        // pindan_list:[],

        pindanPanel:{
            product_id:0,
            notice:0,
            show:0
        },

        pindan_swiper:[
            // [1,2],
            // [3,4],
            // [5]
        ],

        comment_list:[],
        starClass : ['', 'one','two','three','four','five'],
        label_active:'detail'
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

        this.setData({
            product_id:options.product_id
        });

        this.init();
    },

    init:function( ){
        //todo 获取 商品详情
        this.product_detail();
        this.get_spec_object();
        this.cartStatus();
        this.get_pindan_list();
        this.get_comment_list();
    },

    poEvent:function( e ){

        this.cartStatus();

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        var p1 = new Promise( this.product_detail );
        var p2 = new Promise( this.get_spec_object );
        var p3 = new Promise( this.cartStatus );
        var p4 = new Promise( this.get_pindan_list );
        var p5 = new Promise( this.get_comment_list );

        var p = Promise.race( [ p1, p2, p3, p4, p5 ]);
        p.then(function( result ){
            wx.stopPullDownRefresh();
        });
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },

    /////////////////  以下为自定义方法 /////////////////////////
    product_detail:function( resolve ){

        var product_id = this.data.product_id;
        var t = this;

        var url = appInstance.globalData.api_path+'&r=goods.info';
        var data= {
            'goods_id' : product_id
        };

        appInstance.request( url, data, 'GET', function( res ){
            var bnrHeight = res.data.image_height * 750 / res.data.image_width;
            t.setData({
                image_list  : res.data.image_list,
                image       : res.data.image,
                name        : res.data.name,
                price       : res.data.price,
                special     : res.data.special,
                sale        : res.data.sale,
                bnrHeight   : bnrHeight,
                description : res.data.description,
                pindan      : res.data.pindan
            });

            if( typeof resolve == 'function'){
                resolve( res.data );
            }
        });

    },

    get_spec_object:function( resolve ){

        var product_id = this.data.product_id;
        var t = this;

        var url = appInstance.globalData.api_path+'&r=goods.specification';
        var data= {
            'goods_id' : product_id
        };

        appInstance.request( url, data, 'GET', function( res ){
            t.setData({
                specification:res.data.specification,
                spec_object:res.data.spec_object
            });
            if( typeof resolve == 'function'){
                resolve( res.data );
            }
        });


    },

    buy:function(){

        if( this.data.spec_object.length ){
            // 打开商品规格面板
            this.open_option_panel( 'buy' );
            return;
        }

        // todo 后期商品规格出来后，需加上弹出面板选择
        wx.navigateTo({
            url:'/pages/checkout/checkout?product_id='+this.data.product_id
        });

    },

    buy_pindan:function( e ){

        var order_id = e.currentTarget.dataset.order_id;
        if( this.data.spec_object.length ){
            // 打开商品规格面板
            this.open_option_panel( 'buy_pindan', order_id );
            return;
        }

        // todo 后期商品规格出来后，需加上弹出面板选择
        wx.navigateTo({
            url:'/pages/checkout/checkout?product_id='+this.data.product_id
        });

    },

    buy_from_pindan_list:function( e ){

        var order_id = e.detail.order_id;
        if( this.data.spec_object.length ){
            // 打开商品规格面板
            this.open_option_panel( 'buy_pindan', order_id );
            return;
        }

    },

    get_pindan_list:function( resolve ){

        var t = this;
        var url = 'checkout.order.pindan_list&goods_id=' + this.data.product_id;

        appInstance.get(url, {}, res=>{

            var item_arr = [];
            res.data.forEach(function( item ){

                item_arr.push( item );
                if(item_arr.length==2){
                    t.data.pindan_swiper.push( item_arr );
                    item_arr = [];
                }
            });

            if( item_arr.length > 0 ){
                t.data.pindan_swiper.push( item_arr );
            }

            t.setData({

                pindan_swiper:t.data.pindan_swiper,
                pindan_number:res.data.length
                // pindan_list:res.data
            });
            if( typeof resolve == 'function'){
                resolve( res.data );
            }

        });

        var interval = setInterval(function(){

            var now = new Date().getTime();

            t.data.pindan_swiper.forEach(function( item_group ){
                item_group.forEach(function( item ){
                    var start_time = new Date( item.start_time.replace('-','/') ).getTime();
                    var end_time = start_time + item.validate_time*3.6e6;
                    var cha = end_time - now;
                    if( cha <= 0 ){

                        clearInterval( interval );
                        t.get_pindan_list();
                    }
                    var days = Math.floor(cha / (24*3600*1000) );

                    //计算出小时数
                    var leave1=cha % (24*3600*1000)    //计算天数后剩余的毫秒数
                    var hours=Math.floor(leave1/(3600*1000))
                    hours = hours<10?'0'+hours:hour;
                    //计算相差分钟数

                    var leave2=leave1%(3600*1000)        //计算小时数后剩余的毫秒数
                    var minutes=Math.floor(leave2/(60*1000))
                    minutes = minutes<10?'0'+minutes:minutes;
                    //计算相差秒数

                    var leave3=leave2%(60*1000)      //计算分钟数后剩余的毫秒数
                    var seconds=Math.round(leave3/1000)
                    seconds = seconds<10?'0'+seconds:seconds;

                    item.remaining = days ?  days + '天':'';
                    item.remaining += hours + ':' + minutes + ':' + seconds;
                });

            });

            t.setData({
                pindan_swiper:t.data.pindan_swiper
            });

        },1000);
    },

    addCart:function( e ){

        if( this.data.spec_object.length ){
            // 打开商品规格面板
            this.open_option_panel( 'add_to_cart' );
            return;
        }

        //todo 调用 加入购物车 API
        //todo 监听购物车数据，更改当前购物车数量

        var product_id = product_id;
        var number = number;

        var url= appInstance.globalData.api_path+'&r=cart.add';

        var data = {
            product_id:this.data.product_id,
            number: 1,
        };
        var t = this;
        appInstance.request( url, data, 'GET', function( res ){

            if( !res.data.status ){
                wx.showToast({
                    title: '购物车添加成功',
                    icon: 'success',
                    duration: 1200
                });

                //todo 更新购物车 状态

                t.cartStatus();
            }



        });

    },

    cartStatus:function( resolve ){


        // todo 获取 购物车 最新状态

        var url = appInstance.globalData.api_path+'&r=cart.index';
        var data = {};
        var t = this;
        appInstance.request(url, data, 'GET', function( res ){

            //todo 刷底部菜单购物车数量值
            var list = res.data.list;

            var cart_total = 0;
            list.forEach(function( item, index ){

                cart_total += parseInt( item.goods_num );

            });

            t.setData({
                cart_total : cart_total
            })
            if( typeof resolve == 'function'){
                resolve( res.data );
            }

        });

    },

    goto_cart:function(){

        
    },

    open_option_panel:function( goto, order_id ){

        this.data.option_panel.notice ++;
        this.data.option_panel.goto = goto;
        this.data.option_panel.pindan_order = order_id?order_id:0;
        this.setData({
            option_panel:this.data.option_panel
        });

    },

    pindanMore:function( e ){

        this.data.pindanPanel.product_id = this.data.product_id;
        this.data.pindanPanel.notice ++;
        this.setData({
            pindanPanel: this.data.pindanPanel
        });


    },

    // 评论列表
    get_comment_list:function(){

        var url = appInstance.globalData.api_path+'&r=goods.comment';
        var data = {
            'goods_id' : this.data.product_id
        };
        var t = this;
        appInstance.request(url, data, 'GET', function( res ){

            t.setData({
                comment_list:res.data
            });

        });

    },

    switch_label:function( e ){

        var label = e.currentTarget.dataset.label;

        this.setData({
            'label_active' : label
        });

    },

    pageClick:function(){

        this.data.option_panel.notice --;
        this.setData({
            option_panel:this.data.option_panel
        });

    }

})